from api.models import Recommend, News
from rest_framework import serializers


class RecommendSubNewsSerializer(serializers.ModelSerializer):
    image_list = serializers.SerializerMethodField()

    class Meta:
        model = News
        fields = ['id', 'title', 'url', 'image_list']

    def get_image_list(self, obj):
        if not obj.image:
            return []
        return obj.image.split(',')


class RecommendSerializer(serializers.ModelSerializer):
    news_info = RecommendSubNewsSerializer(source='news', read_only=True)

    class Meta:
        model = Recommend
        fields = ['id', 'news', 'news_info']
        extra_kwargs = {'news': {'write_only': True}}
